import React from 'react';

import '@fortawesome/fontawesome-free/css/all.css';
import '@fortawesome/fontawesome-free/css/v4-shims.css';

import 'amis/lib/themes/cxd.css';
import 'amis/lib/helper.css';
import 'amis/sdk/iconfont.css';

import axios from 'axios';
import copy from 'copy-to-clipboard';
import $http from './request'

import {render as renderAmis, ToastComponent, AlertComponent} from 'amis';
import {alert, confirm, toast} from 'amis-ui';

var businessCode: string|null;
var itemCode: string | null;
var action: string | null;
var executeVO: any | null
// amis 环境配置
const env = {
  theme: 'cxd', // cxd 或 antd,
  // 下面三个接口必须实现
  fetcher: ({
    url, // 接口地址
    method, // 请求方法 get、post、put、delete
    data, // 请求数据
    responseType,
    config, // 其他配置
    headers // 请求头
  }: any) => {
    debugger
    config = config || {};
    config.withCredentials = true;
    responseType && (config.responseType = responseType);

    if (config.cancelExecutor) {
      config.cancelToken = new (axios as any).CancelToken(
        config.cancelExecutor
      );
    }

    config.headers = headers || {};

    if (method !== 'post' && method !== 'put' && method !== 'patch') {
      if (data) {
        config.params = data;
      }
      return (axios as any)[method](url, config);
    } else if (data && data instanceof FormData) {
      config.headers = config.headers || {};
      config.headers['Content-Type'] = 'multipart/form-data';
    } else if (
      data &&
      typeof data !== 'string' &&
      !(data instanceof Blob) &&
      !(data instanceof ArrayBuffer)
    ) {
      data = JSON.stringify(data);      
      config.headers = config.headers || {};
      config.headers['Content-Type'] = 'application/json';
    }
    
    config.headers['X-Token'] = localStorage.getItem('token')
    if(action==='create' || action==='modify'){
      data = {businessCode:businessCode,content:data,starter:'admin'}
    }else if (action==='approval') {
      data = {businessCode:businessCode,content:data,approver:'admin',executeVO:{...executeVO,assignee:'admin',nextAssignee:'admin'}}
    }
    

    return (axios as any)[method](url, data, config);
  },
  isCancel: (value: any) => (axios as any).isCancel(value),
  copy: (content: string) => {
    copy(content);
    toast.success('内容已复制到粘贴板');
  }

  // 后面这些接口可以不用实现

  // 默认是地址跳转
  // jumpTo: (
  //   location: string /*目标地址*/,
  //   action: any /* action对象*/
  // ) => {
  //   // 用来实现页面跳转, actionType:link、url 都会进来。
  // },

  // updateLocation: (
  //   location: string /*目标地址*/,
  //   replace: boolean /*是replace，还是push？*/
  // ) => {
  //   // 地址替换，跟 jumpTo 类似
  // },

  // isCurrentUrl: (
  //   url: string /*url地址*/,
  // ) => {
  //   // 用来判断是否目标地址当前地址
  // },

  // notify: (
  //   type: 'error' | 'success' /**/,
  //   msg: string /*提示内容*/
  // ) => {
  //   toast[type]
  //     ? toast[type](msg, type === 'error' ? '系统错误' : '系统消息')
  //     : console.warn('[Notify]', type, msg);
  // },
  // alert,
  // confirm,
};

const defaultApprovalTemplate:any =  {
  type: "page",
  title: "",
  body: [
    {
      id: "u:f4abf59359e7",
      type: "form",
      title: "审批",
      mode: "horizontal",
      dsType: "api",
      feat: "Insert",
      body: [
        {
          type: "radios",
          label: "结果",
          name: "action",
          options: [
            {
              label: "同意",
              value: true
            },
            {
              label: "不同意",
              value: false
            }
          ],
          id: "u:7db1252e9ddf",
          value: ""
        },
        {
          type: "textarea",
          label: "意见",
          name: "opinion",
          id: "u:e97c74feb1a3",
          minRows: 3,
          maxRows: 20
        }
      ],
      actions: [
        {
          type: "button",
          label: "提交",
          onEvent: {
            click: {
              actions: [
                {
                  actionType: "submit",
                  componentId: "u:f4abf59359e7"
                }
              ]
            }
          },
          level: "primary",
          id: "u:32e343938b45"
        }
      ],
      resetAfterSubmit: true,
      api: {
        url: "/project/api/approval",
        method: "post",
        requestAdaptor: "",
        adaptor: "",
        messages: {},
        dataType: "json"
      }
    }
  ],
  id: "u:97f0730c4361",
  asideResizor: false,
  pullRefresh: {
    disabled: true
  }
};

const approvalHistoryTemplate = {
  type: "page",
  title: "",
  body: [
    {
      type: "tabs",
      tabs: [
        {
          title: "流程",
          body: [
            {
              type: "html",
              html: "${flowImage}"
            }
          ],
          id: "u:9aa66f947729"
        },
        {
          title: "审批记录",
          body: [
            {
              type: "table",
              columns: [
                {
                  label: "节点名称",
                  name: "flowTaskName",
                  type: "text",
                  id: "u:e33cb102c14a"
                },
                {
                  type: "text",
                  label: "审批人",
                  name: "approver",
                  id: "u:3d85470ba160"
                },
                {
                  type: "text",
                  name: "taskCreateTime",
                  label: "发起时间",
                  id: "u:a8e884081809"
                },
                {
                  type: "text",
                  label: "审批完成时间",
                  name: "taskEndTime",
                  id: "u:ed26e0b30145"
                }
              ],
              id: "u:adaa581604c7",
              source: "${approvalList}"
            }
          ],
          id: "u:a7778def423c"
        }
      ],
      id: "u:b13b6cd7c240"
    }
  ],
  id: "u:97f0730c4361",
  asideResizor: false,
  pullRefresh: {
    disabled: true
  }
}
function getApprovalHistoryTemplate(flowImage:string){
  return {
    type: "page",
    title: "",
    body: [
      {
        type: "tabs",
        tabs: [
          {
            title: "流程",
            body: [
              {
                type: "html",
                html: flowImage
              }
            ],
            id: "u:9aa66f947729"
          },
          {
            title: "审批记录",
            body: [
              {
                type: "table",
                columns: [
                  {
                    label: "节点名称",
                    name: "flowTaskName",
                    type: "text",
                    id: "u:e33cb102c14a"
                  },
                  {
                    type: "text",
                    label: "审批人",
                    name: "approver",
                    id: "u:3d85470ba160"
                  },
                  {
                    type: "text",
                    name: "taskCreateTime",
                    label: "发起时间",
                    id: "u:a8e884081809"
                  },
                  {
                    type: "text",
                    label: "审批完成时间",
                    name: "taskEndTime",
                    id: "u:ed26e0b30145"
                  }
                ],
                id: "u:adaa581604c7",
                source: "${approvalList}"
              }
            ],
            id: "u:a7778def423c"
          }
        ],
        id: "u:b13b6cd7c240"
      }
    ],
    id: "u:97f0730c4361",
    asideResizor: false,
    pullRefresh: {
      disabled: true
    }
  }
}

function getEmptyTemplate(level:any, message:any){
  return {
    type: "page",
    title: "",
    body: [
      {
        type: "alert",
        body: [
          {
            type: "tpl",
            tpl: message,
            wrapperComponent: "",
            inline: false,
            id: "u:810aac3e87c5"
          }
        ],
        level: level,
        id: "u:65e60c1c3814"
      }
    ],
    id: "u:97f0730c4361",
    asideResizor: false,
    pullRefresh: {
      disabled: true
    },
    toolbar: [
    ],
    aside: [
    ]
  }
};

class AMISComponent extends React.Component<any, any> {
  render() {
    return renderAmis(
      // 这里是 amis 的 Json 配置。
      this.props.template,
      {
        data: this.props.data,
        context: this.props.context
      },
      env
    );
  }
}

class APP extends React.Component<any, any> {

  data: any = {};

  state = {formTemplate: {type: 'page',body:{}},formData:{}, flowImage:null, approvalList: null, error: null};

  constructor(props: any){
    super(props);
    console.log('constructor')
    // debugger
    // demo http://localhost:9000/?businessCode=1234567890&itemCode=TEST_00001&action=modify
    const params = new URLSearchParams(window.location.search);
    businessCode = params.get('businessCode');
    itemCode = params.get('itemCode');
    action = params.get('action');
    if(businessCode&&itemCode&&action){
      this.getCodeData(businessCode,itemCode,action)
    }
  }

  // 获取验证码信息
  getCodeData = (businessCode:string,itemCode:string,action:string) => {
    // axios 请求案例
    $http.get(`/project/api/business/${businessCode}/${itemCode}/${action}`).then(
      response => {
        console.log("请求成功了！", response.data) // 请求成功，打印一下数据
        this.data = response.data.data;
        if(this.data&&this.data.formTemplate&&this.data.formTemplate.content){
          let form = JSON.parse(this.data.formTemplate.content)
          this.setState({
            formTemplate: {type: 'page', body:form},
            formData: JSON.parse(this.data.formData||'{}')
          });
          executeVO = this.data.executeVO
          if(action!='create'){
            this.getApprovalList()
            if(executeVO && executeVO.processInstanceId) {
              this.getFlowImage(executeVO.processInstanceId,executeVO.tenantId)
            }
          }          
        }else{
          this.setState({error:response.data.msg?response.data.msg:'未知错误'})
        }
      },
      error => {
        console.log("请求失败了！", error) // 请求失败，打印一下错误
        this.setState({error:error.message})
      }
    )
  }

  getFlowImage = (processId:string,tenantId:string) => {
    $http.get(`/flow/process/getImageByProcessInstanceId/${processId}?tenantId=${tenantId}`).then(
      response => {
        if(response.data){
          this.setState({flowImage: response.data})
        }
      }
    )
  }

  getApprovalList = () => {
    $http.get(`/project/api/historyBusinessData/list?businessCode=${businessCode}`).then(
      response => {
        console.log(response.data)
        if(response.data&&response.data.data){
          this.setState({approvalList: response.data.data.reverse()})
        }
      }
    )
  }

  render() {
    return ( 
      <>
        <ToastComponent key="toast" position={'top-right'} />
        <AlertComponent key="alert" />
        <AMISComponent template={this.state.error? getEmptyTemplate('danger', this.state.error) : this.state.formTemplate }
          data={this.state.formData} context={{action:action}}/>
        {action==='approval' && (<AMISComponent template={defaultApprovalTemplate} />)}
        {this.state.flowImage && this.state.approvalList && (<AMISComponent template={getApprovalHistoryTemplate(this.state.flowImage)} 
          data= {{approvalList: this.state.approvalList}} />)}
      </>
    ) 
  }
}

export default APP;
